package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    //注入序列化器进行序列化
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo sendCode() {
        //生成验证码 新建一个specCaptcha用来创建一个验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);//指定具体生成什么类型
        String img = specCaptcha.toBase64();//获取验证码的图片返回字符串
        String text = specCaptcha.text();//获取验证码生成的内容

        //把验证码的值存到redis中
        String replace = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(replace,text,120, TimeUnit.SECONDS);
        //拼接验证码和图片
        CaptchaVo captchaVo = new CaptchaVo(img, replace);
        return captchaVo;
    }


    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        //解析token
        Claims claims = JwtUtil.parseToken(accessToken);
        //获取userId(claim会把整数类型都认作int类型)
        Integer userId = (Integer) claims.get("userId");
        //用id查询数据
        SystemUser systemUser = systemUserService.getById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        //检查验证码是否过期
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        //如果redis为null抛异常
        if (ObjectUtils.isEmpty(redisCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //验证码是否正确
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())){
            //不正确抛异常
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //账号是否存在
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser one = systemUserService.getOne(systemUserLambdaQueryWrapper);

        //判断
        if (one == null){
            //账号不存在
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //检查密码是否正确
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!one.getPassword().equals(password)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //检查账号是否可用
        if (one.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //都没问题创建token
        String token = JwtUtil.createToken(one.getId(),one.getUsername());
        return token;
    }
}
